angular.module('starter.zjrController', [])

//自金融
.controller('ZjrCtrl', function($rootScope,$location,$sce,$ionicLoading,$ionicModal,$ionicPopover,$window,$state,ZjrProduceService,$scope,$ionicPopup,UserService,$ionicScrollDelegate,$ionicSideMenuDelegate,$timeout) {
/*	 $scope.toggleLeftSideMenu = function() {
    $ionicSideMenuDelegate.toggleRight();
  };*/
      //跳转到用户的征信报告
   	try{
		if($rootScope.goLookCredit==1){
			$rootScope.goLookCredit=0;
		
			$state.go("tab.zjrCreditCheck",{customerId:$rootScope.lookCredit});		
		 }	
	}catch(error){
	}
	$scope.$on('$ionicView.enter', function(event, data) {
		$ionicLoading.show({
  			template: '加载中...'
		});
		
		//1秒钟后自动销毁
		$timeout(function(){
			$ionicLoading.hide();
        },1000);
	})
	//信用身价增长公告
	$scope.showGG=function(){
		$scope.ggUrl=$sce.trustAsResourceUrl("https://mp.weixin.qq.com/s/jJHeH_RzCVSw9FkoLjS3dA");
		$ionicModal.fromTemplateUrl('templates/zjr/new-gg.html', {
		    scope: $scope,
		    animation: 'slide-in-up'
		}).then(function(modal) {
		    $scope.modal = modal;
		    $scope.modal.show();
		});
				//返回监听
		$scope.cancelBack=function(){
			$scope.modal.hide();
		}
	}
	//51假期业务受理公告
    $scope.showGG1=function(){
		$scope.ggUrl=$sce.trustAsResourceUrl("http://mp.weixin.qq.com/s/kylKBDhDQfn0Kb_DaNenKg");
		$ionicModal.fromTemplateUrl('templates/zjr/new-gg1.html', {
		    scope: $scope,
		    animation: 'slide-in-up'
		}).then(function(modal) {
		    $scope.modal1 = modal;
		    $scope.modal1.show();
		});	
		
		//返回监听
		$scope.cancelBack=function(){
			$scope.modal1.hide();
		}	
}

	//机器人小赖
   $scope.showGG3=function(){
		$scope.ggUrl=$sce.trustAsResourceUrl("http://www.v5kf.com/public/chat/chat?sid=125248&entry=5&ref=link");
		$ionicModal.fromTemplateUrl('templates/zjr/new-gg3.html', {
		    scope: $scope,
		    animation: 'slide-in-up'
		}).then(function(modal) {
		    $scope.modal2 = modal;
		    $scope.modal2.show();
		});	
		
		//返回监听
		$scope.cancelBack=function(){
			$scope.modal2.hide();
			$state.go("tab.zjr");
		}	
}
 	//幸运大转盘
   $scope.showGG4=function(){
		$scope.ggUrl=$sce.trustAsResourceUrl("http://mp.weixin.qq.com/s/NFtzDpk8vo6djb_t7nSQAQ ");
		$ionicModal.fromTemplateUrl('templates/zjr/new-gg4.html', {
		    scope: $scope,
		    animation: 'slide-in-up'
		}).then(function(modal) {
		    $scope.modal2 = modal;
		    $scope.modal2.show();
		});	
		
		//返回监听
		$scope.cancelBack=function(){
			$scope.modal2.hide();
			$state.go("tab.zjr");
		}	
   }
    //玩转好友二级邀请
   $scope.showGG5=function(){
		//$scope.ggUrl=$sce.trustAsResourceUrl("http://mp.weixin.qq.com/s/NFtzDpk8vo6djb_t7nSQAQ ");
		$ionicModal.fromTemplateUrl('templates/zjr/new-gg5.html', {
		    scope: $scope,
		    animation: 'slide-in-up'
		}).then(function(modal) {
		    $scope.modal2 = modal;
		    $scope.modal2.show();
		});	
		
		//返回监听
		$scope.cancelBack=function(){
			$scope.modal2.hide();
			$state.go("tab.zjr");
		}	
   }
   

	//用户等级说明
	$scope.showMe = function(){
		var html = "<div>【<font style='font-weight:bold;'>用户等级说明</font>】</div>"
           + "<div>Lv是平台用户等级标识,等级不同最高可借额度不同,等级提升规则到“帮助”中查看。</div>"
		   + "<div>【<font style='font-weight:bold;'>粉丝说明</font>】</div>"
		   +"<div>1.借款人还款后,出借人可关注还款人成为其粉丝,粉丝可提高借款成功率.</div><div> 2.借款人获得一个粉丝，信用身价+30，失去一个粉丝，信用身价-30</div> <div>3.借款人逾期,逾期5天后,系统自动清空所有粉丝.</div>"
		   +"<div>【<font style='font-weight:bold;'>皇冠说明</font>】</div>"
		   +"<div>提前王：借款人连续15次以上提前还款.</div><div> 守时王：借款人连续15次以上按时还款(含提前还款).</div><div> 借款人逾期,提前王和守时王标记消失,从零开始记录重新封王. 数据每日凌晨统计刷新.</div>"
		   +"<div style='margin-top:10px;'>信用,才是您最高贵的财富!</div> "
		
		$ionicPopup.alert({
			title:'用户等级说明',
			template:html,
			cssClass:'my-custom-popup'
		});
	}

	//短贷为0，长贷为1
	$scope.isDuan=0;
	//姓名
	var searchName=null;
	//筛选条件
	var duanFilter=null;
	var changFilter=null;
	
	//长短贷切换
	$scope.changeDuan=function(num){
		$scope.isDuan=num;
		if(num==1){
			$ionicScrollDelegate.$getByHandle('changScroll').scrollTop();
		}
		
		
	}
	
	//按钮颜色切换
	$scope.searchBtn=0;
	$scope.changSearchBtn=function(){
		var searchName=$scope.searchName;
		if(searchName!=null&&searchName!=''){
			$scope.searchBtn=1;
		}else{
			var duanPage=0;
			$scope.changNoMore=true;
			$scope.duanNoMore=true;
			$scope.searchBtn=0;
		}
	}
	
	//打开右侧栏目
	$scope.toggleRight = function() {
	    $ionicSideMenuDelegate.toggleRight();
	};
	
	//短贷筛选更换
	$scope.changeDuanFilter=function(f){
		if(f==undefined){
		$scope.changFilter1=8;
		}else{
		$scope.changFilter1=9;
		}
		duanPage=0;
		$scope.duanFilter=f;
		$scope.isDuan=0;//先查短贷
		$scope.duanNoMore=true;
		
		//清空查询列表
		$scope.duanProduces=[];

		$scope.loadDuanProduces();
	}
	
	//长贷筛选更换
	$scope.changeChangFilter=function(f){
		changPage=0;
		$scope.changFilter=f;
		$scope.isDuan=1;//先查长贷
		$scope.changNoMore=true;
		
		//清空查询列表
		$scope.changProduces=[];

		$scope.loadChangProduces();

	}
	
	//查询短贷数据
	//初始化短贷page为0,加载更多默认开启
	var duanPage=0;
	$scope.duanNoMore=true;
	$scope.duanProduces=[];
	$scope.hlduanProduces=[];
/*	$scope.duanProducesUserId=[];*/
/*	$scope.test={customerId:'',age:''};*/
	$scope.gogo==0;
	$scope.loadDuanProduces=function(){

		ZjrProduceService.getProduceList(duanPage,$scope.searchName,$scope.duanFilter).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
			if(response.data!=null&&response.data!=''){
				if(response.data.length<=0){
					$scope.duanNoMore=false;
				}else{	
					if(($scope.changFilter1>0 ||$scope.changFilter>0)&&$scope.duanProduces.length!=$scope.hlduanProduces.length){
						$scope.hlduanProduces=[];
					}
					for(var i=0;i<response.data.length;i++){
/*						$scope.test.customerId=response.data[i].userId
						$scope.duanProducesUserId.push($scope.test);*/					
						 $scope.duanProduces.push(response.data[i]);
				          ZjrProduceService.getRegisterDayNumber(response.data[i].userId).then(function(response1) {
                          $scope.hlduanProduces.push(response1.data);
                          for(var i=0;i<$scope.duanProduces.length;i++){
								if($scope.duanProduces[i].userId==response1.data.customerId){
										 $scope.duanProduces[i].sort=response1.data.userAccountAge;
		                 }								
						}
                                               
			     });	
				}								
/*                console.log($scope.duanProducesUserId); 
                 
                $scope.duanProducesUserIds = angular.toJson($scope.duanProducesUserId, true);
                 console.log($scope.duanProducesUserIds);*/ 
					duanPage=duanPage+1;
		        }	

				
			}else{
				$scope.duanNoMore=false;
			}
			
		});
	}
	
	//查询长贷数据
	//初始化短贷page为0,加载更多默认开启
	var changPage=0;
	$scope.changNoMore=true;
	$scope.changProduces=[];
	$scope.chlduanProduces=[];
	$scope.loadChangProduces=function(){
		ZjrProduceService.getLongProduceList(changPage,$scope.searchName,$scope.changFilter).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
			if($scope.searchName==undefined){
				
			}
			if(response.data!=null&&response.data!=''){
				if(response.data.length<=0){
					$scope.changNoMore=false;
				}else{
	          console.log(response);
					for(var i=0;i<response.data.length;i++){
						$scope.changProduces.push(response.data[i]);
					 ZjrProduceService.getRegisterDayNumber(response.data[i].userId).then(function(response1) {
                            for(var i=0;i<$scope.changProduces.length;i++){
								if($scope.changProduces[i].userId==response1.data.customerId){
										 $scope.changProduces[i].type=response1.data.userAccountAge;
		                 	}
						}
                           
			      });
					}
				changPage=changPage+1;	        
				}
			}else{
			$scope.changNoMore=false;
			if($scope.searchName!=undefined){

			 }
				
			}
			
			
		});
	}
	
	
	//根据姓名查询
	$scope.search=function(name){
		if(name=='' || name==undefined){
		$scope.duanNoMore=true;
		//先清空数据
		$scope.duanProduces=[];
		$scope.hlduanProduces=[];
		//重新查询数据
		ZjrProduceService.getProduceList(0,$scope.searchName,$scope.duanFilter).then(function(response) {
			for(var i=0;i<response.data.length;i++){
				$scope.duanProduces.push(response.data[i]);
		       ZjrProduceService.getRegisterDayNumber($scope.duanProduces[i].userId).then(function(response1) {
/*                     $scope.hlduanProduces.push(response1.data);
                     if($scope.duanProduces.length==$scope.hlduanProduces.length){                    	
                     	          $scope.loadAge();
                     }*/
                       for(var i=0;i<$scope.duanProduces.length;i++){
								if($scope.duanProduces[i].userId==response1.data.customerId){
										 $scope.duanProduces[i].sort=response1.data.userAccountAge;
		                 	}
						}
			     });
			 }
			
		});
		  return;
		}
		//先清空数据
		$scope.duanProduces=[];
		$scope.hlduanProduces=[];
		//重新查询数据
		ZjrProduceService.getProduceList(0,$scope.searchName,$scope.duanFilter).then(function(response) {
			for(var i=0;i<response.data.length;i++){
				$scope.duanProduces.push(response.data[i]);
		       ZjrProduceService.getRegisterDayNumber($scope.duanProduces[i].userId).then(function(response1) {
/*                     $scope.hlduanProduces.push(response1.data);
                     if($scope.duanProduces.length==$scope.hlduanProduces.length){
                     	       $scope.loadAge(); 
                     }*/
                            for(var i=0;i<$scope.duanProduces.length;i++){
								if($scope.duanProduces[i].userId==response1.data.customerId){
										 $scope.duanProduces[i].sort=response1.data.userAccountAge;
		                 	}
						}
                          
			     });
			 }	

       
		});	
	}
      	$timeout(function(){	
         $scope.changeDuan(0);
        },1000);
      //短贷加载年龄
		$timeout(function(){	
		try{
         $scope.changeDuan(0);
         $ionicScrollDelegate.$getByHandle('changScroll').scrollTop();				
		}catch(e){

		}
					
        },1000);
       $scope.loadAge=function(){ 
       	$timeout(function(){
       	try{
  
		 for(var i=0;i<$scope.duanProduces.length;i++){
			if($scope.duanProduces[i].userId==$scope.hlduanProduces[i].customerId){
					 $scope.duanProduces[i].sort=$scope.hlduanProduces[i].userAccountAge;
			}		
		}
		}catch(e){

		}	
		$scope.gogo=1;
        },1000);
       	
       }
        //长待加载年龄
       $scope.cloadAge=function(){
      	$timeout(function(){		
		for(var i=0;i<$scope.wlduanProduces.length;i++){					
		 $scope.duanProduces[i].sort=$scope.hlduanProduces[i];
		}
		$scope.gogo=1;
        },1000);
       	
       } 
   
})

//添加产品
.controller('AddProduceController', function($ionicLoading,$scope,ionicDatePicker,$window,$state,$ionicPopup,ZjrProduceService,$ionicModal,CreditService) {
		
	//可用身价
	var creditValue=0;
	$scope.creditValue=creditValue;
	
	$scope.$on('$ionicView.beforeEnter', function(event, data) {
		var userId=null;
		var token=null;
		try{
			userId=JSON.parse($window.localStorage["user"] || '{}').userId;
			token=JSON.parse($window.localStorage["user"] || '{}').token;
		}catch(e){
			
		}
		
		//验证登录
		if(userId==null||token==null||userId==''||token==''){
			$state.go('login');
			return ;
		}
		
		//验证实名绑卡，必填类，运营商实名认证，运营商数据分析
		var isCertificate=0;
		var generalInfoStatus=0;
		var mnoStatus=0;
		var mnoAccountStatus=0;
		
		CreditService.getCreditExamineStatus().then(function(response) {
			if(response.success=='success'){
				isCertificate=response.data.isCertificate;
				generalInfoStatus=response.data.generalInfoStatus;
				mnoStatus=response.data.mnoStatus;
				mnoAccountStatus=response.data.mnoAccountStatus;
				$scope.examineStatus=response.data;

				//是否实名绑卡、必填类、运营商认证
				if($scope.examineStatus.isCertificate==1 &&$scope.examineStatus.generalInfoStatus==2&&$scope.examineStatus.mnoStatus==1 && $scope.examineStatus.mnoAccountStatus==1){			
				
			    }else{
					//跳转到实名认证，必填类，运营商认证界面
					$state.go('tab.isAuthentication');
				}
			}else{
				//跳转到实名认证，必填类，运营商认证界面
				$state.go('tab.isAuthentication');
			}
		});
		
		//查询信用身价
		CreditService.getCreditLevel().then(function(response) {
			$scope.creditLevel=response.data.creditLevel;
			$scope.xyCreditValue=response.data.creditValue;
			if(response.success=="success"){
/*				if(response.data.creditValue<1000){
					$state.go('tab.addXsb');
				}*/
			}
		});
		
		//查询可用额度
		ZjrProduceService.getAvailableCreditValue().then(function(response) {
			if(response.success=="success"){
				if(response.data<0){
					creditValue=0;
				}else{
					creditValue=response.data;
				}
				
				$scope.creditValue=creditValue;
			}
		});
		
		//获取最低年利率
		ZjrProduceService.getLevel().then(function(response) {
			if(response.success=="success"){
				//最小年利率
				$scope.minInterestRates=response.data*100;
				$scope.produce.longInterestRates=response.data*100;
				$scope.placeholder='每一千元日利息'+parseFloat((1000*$scope.produce.longInterestRates)/100/360).toFixed(2) +'元(年化'+parseInt($scope.produce.longInterestRates)+'%)';
			}
		});
		
	});
	
	//默认进入短贷模式
	$scope.isDuan=1;
	
	//切换长短贷
	$scope.changeSel=function(v){
		$scope.isDuan=v;
	}
	
	//定义数据实体
	$scope.produce={};
	
	//约为多少钱
	$scope.appointment=0;
	$scope.appointmentChange=function(){
		// 今天日期
		var nowDate=new Date().getFullYear()+"-"+(new Date().getMonth()+1)+"-"+new Date().getDate(); 
		console.log(nowDate);
		//截止日期减当天时间
        var days = new Date($scope.produce.deadTime).getTime()-new Date(nowDate).getTime();
        if(isNaN(days)){
        	try{
        		days=new Date($scope.produce.deadTime.replace(/\-/g,"/")).getTime()-new Date(nowDate.replace(/\-/g,"/")).getTime();
        	}catch(e){
        		
        	}
        }
        //天数（当天到要借款那天的天数）
		var deadDays=parseInt(days/(1000 * 60 * 60 * 24))+1;
	    //到期后利息=借款金额*（(年利息/100/360)*天数）
		$scope.appointment=$scope.produce.totalPrice*(($scope.produce.interestRates/100/360)*deadDays);
	}
	//var hkTip;
	//滑动滑块验证
	$scope.appointmentChangeh=function(){
	    //验证借款金额
		if($scope.produce.totalPrice==null||$scope.produce.totalPrice==''){
			$scope.hkTip='请先填写借款金额';
		
		}else if($scope.produce.deadTime==null||$scope.produce.deadTime==''){
			$scope.hkTip='请先填写还款日期';
			
		}else{
			$scope.hkTip='';
		}
	

		// 今天日期
		var nowDate=new Date().getFullYear()+"-"+(new Date().getMonth()+1)+"-"+new Date().getDate(); 
		console.log(nowDate);
		//截止日期减当天时间
        var days = new Date($scope.produce.deadTime).getTime()-new Date(nowDate).getTime();       
        if(isNaN(days)){
        	try{
        		days=new Date($scope.produce.deadTime.replace(/\-/g,"/")).getTime()-new Date(nowDate.replace(/\-/g,"/")).getTime();
        	}catch(e){
        		
        	}
        }
        //天数（当天到要借款那天的天数）
		var deadDays=parseInt(days/(1000 * 60 * 60 * 24))+1;
	    //到期后利息=借款金额*（(年利息/100/360)*天数）
		$scope.appointment=$scope.produce.totalPrice*(($scope.produce.interestRates/100/360)*deadDays);
	}
	
	
	//年利率变化
	$scope.placeholderChange=function(produce){
		if(produce.longInterestRates<$scope.minInterestRates){
			produce.longInterestRates=$scope.minInterestRates;
			$scope.produce.longInterestRates=$scope.minInterestRates;
		}
		$scope.placeholder='每一千元日利息'+parseFloat((1000*produce.longInterestRates)/100/360).toFixed(2)+'元(年化'+parseInt(produce.longInterestRates)+'%)';
		//计算每期还款
		$scope.appointmentChang=produce.totalPrice/produce.period+((produce.totalPrice*produce.longInterestRates)/100/360)*30;
	}
	
	//借不到钱
	$scope.toTip = function(){
		$state.go('tab.addProduceTip');
	}
	
	//保存短贷产品
	$scope.addProduce=function(produce){
		var tipStr='';
		//利率大于或等于1000%的借款标提示
		if(produce.interestRates>=1000){
			tipStr='用户你好,你的借款利率是'+produce.interestRates+'%，你确定要发布吗';
		}else{
			tipStr='你确定发布该借款信息吗?';
		}
		
		//验证借款金额
		if(produce.totalPrice==null||produce.totalPrice==''){
			$ionicPopup.alert({title:'系统提示',template:'借款金额不能为空'});
			return ;
		}
		
		//验证借款金额
		var r = /^\+?[1-9][0-9]*$/;
		if(!r.test(produce.totalPrice)){
			$ionicPopup.alert({title:'系统提示',template:'金额输入错误'});
			return ;
		}
		
		//金额不能大于信用身价
		if(produce.totalPrice>creditValue){
			$ionicPopup.alert({title:'系统提示',template:'借款金额不能大于可借款额度'});
			return ;
		}
		
		if(produce.totalPrice%100!=0){
			$ionicPopup.alert({title:'系统提示',template:'借款金额只能为100的倍数'});
			return ;
		}
		
		//验证年利率
		if(produce.interestRates==null||produce.interestRates==''){
			$ionicPopup.alert({title:'系统提示',template:'年利率不能为空'});
			return ;
		}
		
		//验证年利率
		if(!r.test(produce.interestRates)){
			$ionicPopup.alert({title:'系统提示',template:'年利率输入错误'});
			return ;
		}
		
		//利率低于150%
		if(produce.interestRates<150){
			$ionicPopup.alert({title:'系统提示',template:'系统经历史数据分析，您当前的设置借款成功率为3%以下，请调整利率为150%以上重试'});
			return ;
		}
		
		//借款用途
		if(produce.memo==null||produce.memo==''){
			$ionicPopup.alert({title:'系统提示',template:'借款用途不能为空'});
			return ;
		}
		
		//还款日期验证
		if(produce.deadTime==null||produce.deadTime==''){
			$ionicPopup.alert({title:'系统提示',template:'请选择还款日期'});
			return ;
		}
		
		//借款发布期验证
		if(produce.limitTime==null||produce.limitTime==''){
			$ionicPopup.alert({title:'系统提示',template:'请选择借款发布期'});
			return ;
		}
		
		if(new Date(produce.deadTime).getTime()<=new Date(produce.limitTime).getTime()){
			$ionicPopup.alert({title:'系统提示',template:'还款日期必须大于借款发布期'});
			return ;
		}
		
		//弹出确认对话款
	    var confirmPopup = $ionicPopup.confirm({
	       title: '用户确认',
	       cancelText: '取消',
	       okText: '确定',
	       template: tipStr
	    });
	    confirmPopup.then(function(res) {
	       if(res) {
       			var loading =  $ionicLoading.show({
	      			template: '系统处理中...'
	    		});
	       		//确认发布
	         	ZjrProduceService.addProduce(produce).then(function(response) {
					if(response.success=="success"){
						$ionicLoading.hide();
						//弹出提示并进行页面跳转
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							$state.go('tab.zjr');
						});
					}else{
						$ionicLoading.hide();
						//只弹出页面提示
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
				},function(e){
					$ionicLoading.hide();
					$ionicPopup.alert({title:'系统提示',template:'连接超时'});
				});
	       }
	    });

	}
	
	//查询还款计划
	$scope.payBackPlan=function(produce){
		$scope.payBackPlans={};

		//验证借款金额
		if(produce.totalPrice==null||produce.totalPrice==''){
			$ionicPopup.alert({title:'系统提示',template:'借款金额不能为空'});
			return ;
		}
		
		//验证借款金额
		var r = /^\+?[1-9][0-9]*$/;
		if(!r.test(produce.totalPrice)){
			$ionicPopup.alert({title:'系统提示',template:'金额输入错误'});
			return ;
		}
		
		//金额不能大于可借款额度
		if(produce.totalPrice>creditValue){
			$ionicPopup.alert({title:'系统提示',template:'借款金额不能大于可借款额度'});
			return ;
		}
		
		//验证金额
		if(produce.totalPrice%100!=0){
			$ionicPopup.alert({title:'系统提示',template:'借款金额只能为100的倍数'});
			return ;
		}
		
		//验证期数
		if(produce.period==null||produce.period==''){
			$ionicPopup.alert({title:'系统提示',template:'期数不能为空'});
			return ;
		}
		
		//验证期数
		if(produce.period<3){
			$ionicPopup.alert({title:'系统提示',template:'期数错误'});
			return ;
		}
		
		//验证日利率
		produce.periodDays=30;
		
		//还款计划查询
	 	ZjrProduceService.getProducePayBackPlan(produce).then(function(response) {
			if(response.success=='success'){
				$scope.payBackPlans=response.data;
			}
			
		});
		
		//打开还款计划
		$ionicModal.fromTemplateUrl('templates/zjr/addPayBackPlans.html', {
		    scope: $scope,
		    animation: 'slide-in-up'
		}).then(function(modal) {
		    $scope.modal = modal;
		    $scope.modal.show();
		});
		
		//关闭还款计划方法
		$scope.closeModal = function() {
		    $scope.modal.hide();
		};
		
	}
	
	var fenQiShow;
	//弹出分期数
	$scope.showFenQi=function(){
		var templateHtml='<ul class="list" style="padding:0px;">';
		for(var i=3;i<=12;i++){
			templateHtml+='<li class="item" ng-click="getFenQi('+i+')" style="height:40px;line-height:40px;padding:0px;">&nbsp;&nbsp;'+i+'个月</li>';
		}
		templateHtml+='</ul>';
		fenQiShow=$ionicPopup.show({title:'请选择分期数',template:templateHtml,scope: $scope});
	}
	
	//获取分期数
	$scope.getFenQi=function(num){
		$scope.produce.period=num;
		
		//计算每期还款
		$scope.appointmentChang=$scope.produce.totalPrice/$scope.produce.period+(($scope.produce.totalPrice*$scope.produce.longInterestRates)/100/360)*30;
		
		fenQiShow.close();
	}
	
	//保存长贷产品
	$scope.addLongProduce=function(produce){
		
		//验证借款金额
		if(produce.totalPrice==null||produce.totalPrice==''){
			$ionicPopup.alert({title:'系统提示',template:'借款金额不能为空'});
			return ;
		}
		
		//验证借款金额
		var r = /^\+?[1-9][0-9]*$/;
		if(!r.test(produce.totalPrice)){
			$ionicPopup.alert({title:'系统提示',template:'金额输入错误'});
			return ;
		}
		
		//金额不能大于可借款额度
		if(produce.totalPrice>creditValue){
			$ionicPopup.alert({title:'系统提示',template:'借款金额不能大于可借款额度'});
			return ;
		}
		
		if(produce.totalPrice%100!=0){
			$ionicPopup.alert({title:'系统提示',template:'借款金额只能为100的倍数'});
			return ;
		}
		
		//验证期数
		if(produce.period==null||produce.period==''){
			$ionicPopup.alert({title:'系统提示',template:'期数不能为空'});
			return ;
		}
		
		//验证期数
		if(produce.period<3){
			$ionicPopup.alert({title:'系统提示',template:'期数错误'});
			return ;
		}
		
		//验证日利率
		
		produce.periodDays=30;
		
		//借款用途
		if(produce.memo==null||produce.memo==''){
			$ionicPopup.alert({title:'系统提示',template:'借款用途不能为空'});
			return ;
		}
		
		//借款发布期验证
		if(produce.limitTime==null||produce.limitTime==''){
			$ionicPopup.alert({title:'系统提示',template:'请选择借款发布期'});
			return ;
		}
		
		//弹出确认对话款
	    var confirmPopup = $ionicPopup.confirm({
	       title: '用户确认',
	       cancelText: '取消',
	       okText: '确定',
	       template: '你确定发布该借款信息吗?'
	    });
	    confirmPopup.then(function(res) {
	       if(res) {
       			var loading =  $ionicLoading.show({
	      			template: '系统处理中...'
	    		});
	       		//确认发布
	         	ZjrProduceService.addLongProduce(produce).then(function(response) {
					if(response.success=="success"){
						$ionicLoading.hide();
						//弹出提示并进行页面跳转
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							$state.go('tab.zjr');
						});
					}else{
						$ionicLoading.hide();
						//只弹出页面提示
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
				},function(e){
					$ionicLoading.hide();
					$ionicPopup.alert({title:'系统提示',template:'连接超时'});
				});
	       }
	    });

	}
	
	    
   var toDate=new Date(); 
   var day3 = new Date();
  day3.setTime(day3.getTime()+24*60*60*1000);	
	//初始化日期控件
	var ipObj1 = {
      callback: function (val) {  //Mandatory
      	var date=new Date(val);
      	var month=(date.getMonth()+1);
      	if(month<10){
      		month="0"+month;
      	}
      	var day=date.getDate();
      	if(day<10){
      		day="0"+day;
      	}
      	
      	//赋值
        $scope.produce.deadTime=date.getFullYear()+"-"+month+"-"+day; 
        var nowDate=new Date().getFullYear()+"-"+(new Date().getMonth()+1)+"-"+new Date().getDate(); 
        var days = new Date(val).getTime()-new Date(nowDate).getTime();
        if(isNaN(days)){
        	try{
        		days=new Date(val.replace(/\-/g,"/")).getTime()-new Date(nowDate.replace(/\-/g,"/")).getTime();
        	}catch(e){
        		
        	}
        }
		var deadDays=parseInt(days/(1000 * 60 * 60 * 24))+1;
		
		//计算到期后利息
		var produce=$scope.produce;
		$scope.appointment=produce.totalPrice*((produce.interestRates/100/360)*deadDays);
      },
      from: day3, //Optional
      to: new Date(toDate.getFullYear(),toDate.getMonth(),toDate.getDate()+25), //Optional
      inputDate: day3,      //Optional
      showTodayButton:false,
      mondayFirst: true,          //Optional
      closeOnSelect: false,       //Optional
      templateType: 'modal'       //Optional
    };

    
    var ipObj2 = {
      callback: function (val) {  //Mandatory
      	var date=new Date(val);   
        $scope.produce.limitTime=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
      },
      from: new Date(), //Optional
      to: new Date(toDate.getFullYear(),toDate.getMonth(),toDate.getDate()+3), //Optional
      inputDate: new Date(),      //Optional
      showTodayButton:false,
      mondayFirst: true,          //Optional
      closeOnSelect: false,       //Optional
      templateType: 'modal'       //Optional
    };

	//弹出日期控件
    $scope.openDatePicker = function(){
      ionicDatePicker.openDatePicker(ipObj1);
    };
    
    //弹出日期控件
    $scope.openDatePicker2 = function(){
      ionicDatePicker.openDatePicker(ipObj2);
    };

})


//添加产品
.controller('AddXsbController', function($ionicModal,$ionicLoading,$scope,ionicDatePicker,$window,$state,$ionicPopup,ZjrProduceService,CreditService) {
	
	$scope.$on('$ionicView.beforeEnter', function(event, data) {
		var userId=null;
		var token=null;
		try{
			userId=JSON.parse($window.localStorage["user"] || '{}').userId;
			token=JSON.parse($window.localStorage["user"] || '{}').token;
		}catch(e){
			
		}
		
		//验证登录
		if(userId==null||token==null){
			$state.go('login');
			return ;
		}
		
		//验证实名绑卡，必填类，运营商实名认证，运营商数据分析
		var isCertificate=0;
		var generalInfoStatus=0;
		var mnoStatus=0;
		var mnoAccountStatus=0;
		
		//这里调用方法
		CreditService.getCreditExamineStatus().then(function(response) {
			if(response.success=='success'){
				isCertificate=response.data.isCertificate;
				generalInfoStatus=response.data.generalInfoStatus;
				// 运营商实名认证状态
				mnoStatus=response.data.mnoStatus;
				//运营商数据分析
				mnoAccountStatus=response.data.mnoAccountStatus;
				
				if(isCertificate==1&&generalInfoStatus==2&&mnoStatus==1&&mnoAccountStatus==1){
			
				}else{
					//跳转到实名认证，必填类，运营商认证界面
					$state.go('tab.isAuthentication');
				}
			}else{
				//跳转到实名认证，必填类，运营商认证界面
				$state.go('tab.isAuthentication');
			}
		});
	});
	  		
	$scope.isOkBtn=true;  		
	//获取后台配置数据
	ZjrProduceService.xsbData().then(function(response){
	
		if(response.success=='success' ){
			//定义数据实体
			$scope.produce={
				"totalPrice":response.data.price,
				"deadTime":null,
				"interestRates":response.data.rate,
				"memo":null,
				"limitTime":new Date(),
			};
			$scope.countXsb=response.data.countXsb;
			$scope.cv=response.data.cv;
		}else{
	  		$scope.isMessage=response.message;
	  		$scope.isOkBtn=false;
		}
	})
	
	//可用身价
	var creditValue=0;
	
	//约为多少钱
	$scope.appointment=0;
	$scope.appointmentChange=function(produce){
		var nowDate=new Date().getFullYear()+"-"+(new Date().getMonth()+1)+"-"+new Date().getDate();
		var days = new Date(produce.deadTime).getTime()-new Date(nowDate).getTime();
		$scope.appointment=produce.totalPrice*((produce.interestRates/100/360)*deadDays);
	}
	
	//查询可用额度
	ZjrProduceService.getAvailableCreditValue().then(function(response) {
		if(response.success=="success"){
			if(response.data<0){
				creditValue=0;
				$scope.creditValue = 0;
			}else{
				creditValue=response.data;
				$scope.creditValue = response.data;
			}
			
		}
	});
	
	//保存产品
	$scope.addXsb=function(produce){
		
		//验证借款金额
		if(produce.totalPrice==null||produce.totalPrice==''){
			$ionicPopup.alert({title:'系统提示',template:'借款金额不能为空'});
			return ;
		}
		
		//验证借款金额
		var r = /^\+?[1-9][0-9]*$/;
		if(!r.test(produce.totalPrice)){
			$ionicPopup.alert({title:'系统提示',template:'金额输入错误'});
			return ;
		}
		
		//金额不能大于信用身价
		if(produce.totalPrice>creditValue){
			$ionicPopup.alert({title:'系统提示',template:'借款金额不能大于可借款额度'});
			return ;
		}
		
		if(produce.totalPrice%50!=0){
			$ionicPopup.alert({title:'系统提示',template:'借款金额只能为50的倍数'});
			return ;
		}
		
		//借款用途
		if(produce.memo==null||produce.memo==''){
			$ionicPopup.alert({title:'系统提示',template:'借款用途不能为空'});
			return ;
		}
		
		//还款日期验证
		if(produce.deadTime==null||produce.deadTime==''){
			$ionicPopup.alert({title:'系统提示',template:'请选择还款日期'});
			return ;
		}
		
		//弹出确认对话款
	    var confirmPopup = $ionicPopup.confirm({
	       title: '用户确认',
	       cancelText: '取消',
	       okText: '确定',
	       template: '你确定发布该借款信息吗?'
	    });
	    confirmPopup.then(function(res) {
	       if(res) {
       			var loading =  $ionicLoading.show({
	      			template: '系统处理中...'
	    		});
	       		//确认发布
	         	ZjrProduceService.addXsb(produce).then(function(response) {
					if(response.success=="success"){
						$ionicLoading.hide();
						//弹出提示并进行页面跳转
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							$state.go('tab.zjr');
						});
					}else{
						$ionicLoading.hide();
						//只弹出页面提示
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
				},function(e){
					$ionicLoading.hide();
				});
	       }
	    });
		
		
	}
	
	    
    var toDate=new Date();
	
	//初始化日期控件
	var ipObj = {
      callback: function (val) {  //Mandatory
      	var date=new Date(val);   
        $scope.produce.deadTime=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(); 
        var nowDate=new Date().getFullYear()+"-"+(new Date().getMonth()+1)+"-"+new Date().getDate(); 
        var days = new Date(val).getTime()-new Date(nowDate).getTime();
		var deadDays=parseInt(days/(1000 * 60 * 60 * 24))+1;
		
		//计算到期后利息
		var produce=$scope.produce;
		$scope.appointment=produce.totalPrice*((produce.interestRates/100/360)*deadDays);
      },
      from: new Date(toDate.getFullYear(),toDate.getMonth(),toDate.getDate()+3), //Optional
      to: new Date(toDate.getFullYear(),toDate.getMonth(),toDate.getDate()+25), //Optional
      inputDate: new Date(toDate.getFullYear(),toDate.getMonth(),toDate.getDate()+3), //Optional
      showTodayButton:false,
      mondayFirst: true,          //Optional
      closeOnSelect: false,       //Optional
      templateType: 'modal'       //Optional
    };

	//弹出日期控件
    $scope.openDatePicker = function(){
      ionicDatePicker.openDatePicker(ipObj);
    };
})


//产品明细
.controller('ProduceDetailDuanController', function($rootScope,$ionicPopup,$ionicModal,$ionicHistory,$ionicLoading,$scope,$stateParams,UserService,$window,$state,ZjrProduceService,LoanService,MyService,InvestmentService) {
	var produceId=$stateParams.produceId;
	
	//查询用户信息,姓名，头像，有无逾期
	ZjrProduceService.getUserDetailByProduceId(produceId,0).then(function(response) {
		if(response.success=="success"){
			$scope.user = response.data;
		}
	});
	
	//投资券获取方式
	$scope.showRule = function(){
		var alertPopup = $ionicPopup.alert({
       		template: '获取方式<br>'+
       		'1.新用户注册成功后,可获得10元投资券.<br>'+
       		'2.借款人粉丝数首次达到10的倍数时可获得10元投资券.<br>'+
       		'3.出借人每日出借人数到达20人，可获得10元投资券.<br>'+
       		'使用方式<br>'+
       		'1.单笔投资中，最多使用2张投资券<br>'+
       		'2.对同一借款人，每日只能一笔投资中使用投资券<br>'+
       		'使用投资卷<br>'+
       		'温馨提示：平台将根据不同情况定期调整使用规则，敬请留意！',
	       	title: '投资券规则',
	       	cssClass:'my-custom-popup'
	    });
	}

	//查询借给他的信息
	LoanService.loanDetailList(produceId,0).then(function(response) {
		if(response.success=="success"){
			$scope.details = response.data;
			if(response.data==null||response.data.length<=0){
				$scope.detailsShow=false;
			}else{
				$scope.detailsShow=true;
			}
		}
	});

	//查询产品信息
	ZjrProduceService.getProduceById(produceId).then(function(response) {
		if(response.success=="success"){
			$scope.produce = response.data;
		}
	});
	$scope.recharge=false;
	var balance=0;
	//查询帐户余额
	MyService.getAccountByUserId().then(function(response) {
		if(response.success=="success"){
			balance=response.data;
			$scope.balance = response.data;
			$scope.listsize=[];
     	//查询投资券有效金额
	     InvestmentService.getLoanRedList(0).then(function(response){
				if(response.data!=null){
					for(var i=0;i<response.data.length;i++){
						if(response.data[i].status==0){
						$scope.listsize.push(response.data[i]);	
						}													
					}
					$scope.inviteSize=$scope.listsize.length;
	                if($scope.inviteSize!=2&&$scope.balance<=40){
	                	//按钮变成去充值
	                	$scope.recharge=true;
	                }
				}
			});
		}
	});

		//去充值
		$scope.goRecharge=function(){
	       	$rootScope.pay=1;
	       	$state.go('tab.my');
	       
		}		
	 $scope.tajShow='hide';
	//验证是否可以借给他
	
	
	//计算到期后收益,并验证金额是否充足，合法。
	$scope.isOk=false;
	$scope.appointment=0;
	 var confirmPopup;
	$scope.brorrowChange=function(loanMoney,produce){
/*	      var b1 =  parseInt($scope.balance)+"";
	      var b2  = parseInt(loanMoney)+"";
		//当用户余额直接少于50的时候
		if($scope.balance<50 ){
		//弹出提示风险和免责提示信息
		if(loanMoney.length==1){
		try{
	 	 confirmPopup.close();
	 	}catch(error){
	 		
	 	}
		   confirmPopup = $ionicPopup.confirm({
	       title: '系统提示',
	       cancelText: '取消',
	       okText: '去充值',
	       template: '余额只有'+$scope.balance+'了！<br />'
	    });	
	    confirmPopup.then(function(res) {
	       if(res) {
	       	$rootScope.pay=1;
	       	$state.go('tab.my');
	       	
	      }
	    });	
		}		
	 }else if(parseInt($scope.balance)<parseInt(loanMoney) && b1.length==b2.length){
	 	try{
	 	 confirmPopup.close();
	 	}catch(error){
	 		
	 	}	  
		   //弹出提示风险和免责提示信息
		   confirmPopup = $ionicPopup.confirm({
	       title: '系统提示',
	       cancelText: '取消',
	       okText: '去充值',
	       template: '余额只有'+$scope.balance+'了！<br />'
	    });	
	    confirmPopup.then(function(res) {
	       if(res) {
	       	$rootScope.pay=1;
	       	$state.go('tab.my');
	       	
	      }
	     });
					
	   }else{
	   	
	   }*/
	 
		$scope.sjfk=loanMoney;
		var days = new Date(produce.deadTime).getTime()-new Date().getTime();
		var deadDays=parseInt(days/(1000 * 60 * 60 * 24))+1;
		$scope.appointment=loanMoney*((produce.interestRates/360)*deadDays);
        $scope.loanMoney=loanMoney;
		//验证帐户余额是否充足
		if(loanMoney!=''&&balance>=loanMoney){
			if(loanMoney>0&&loanMoney%50==0){
				$scope.isOk=true;
			}else{
				$scope.isOk=false;
			}
		}else{
			$scope.isOk=false;
		}
		if(loanMoney==''){
			$scope.tajShow='hide';
		}else{
			$scope.tajShow='show';	
		}
	}
	
	//定义选择的投资卷,默认为集合对象
	var loanred=new Array();
	$scope.loanred=loanred;
	
	//初始化投资券分页信息
	var page=0;
	$scope.noMore=true;
	$scope.list=[];
	
	//使用投资券金额
	$scope.loanRedAmt = 0;
	//应扣金额
	$scope.realCost = 0;
	
	//打开投资券页面
	$scope.getLoanRedList=function(){
		
		//加载投资券数据
		$scope.loadList=function(){
			//查询投资券数据
			InvestmentService.getLoanRedList(page).then(function(response){
				$scope.$broadcast('scroll.infiniteScrollComplete');
				$scope.countData = response.countData;
				if(response.data!=null){
					if(response.data.length<=0){
						$scope.noMore=false;
						if(page==0){
							$scope.noData=true;
						}
					}else{										
						for(var i=0;i<response.data.length;i++){
							$scope.list.push(response.data[i]);														
						}
						page=page+1;
					}
				}
			});
		}
		
		//初始化投资券页面
		$ionicModal.fromTemplateUrl('templates/zjr/tzq.html', {
		    scope: $scope
		}).then(function(modal) {
		    $scope.modal = modal;
		    $scope.modal.show();
		});
	  	//关闭投资券方法
		$scope.closeModal = function() {
		//付款金额=用户输入金额+上投资卷金额	
		//验证帐户余额是否充足
		var loanMoney = parseInt($scope.loanMoney);
		//投资券id
		var reds = new Array();
		angular.forEach($scope.loanred,function(data,index,array){
			reds.push(data.id);
		})
		 var num =0;
		 if(reds.length==0){
		 	num=0;
		 }
		 if(reds.length==1){
		 	num=5;
		 }
		 if(reds.length==2){
		 	num=10;
		 }
		 if(balance>=50){
		 	
		 }
          var allMoney=balance+num;
          if(num!=0){
	        if(reds.length==1){
			 	num=5;		 
			$scope.sjfk=loanMoney-5;
			 }
			 if(reds.length==2){

			 	num=10;
			  $scope.sjfk=loanMoney-10;
			 }
          }else{
          	$scope.sjfk=loanMoney;
          }
		 if(loanMoney!=''&&allMoney>=loanMoney){

			if(loanMoney>0&&loanMoney%50==0){
				$scope.isOk=true;
			}else{
				$scope.isOk=false;
			}
		}else{
			$scope.isOk=false;
		}
		
		    $scope.modal.hide();
		};
		
		//选中投资券
		$scope.changeChoice=function(index,loanRecordId){
			//如果当前状态为选中状态
			if($scope.list[index].choice){
				//更改为未选中状态
				$scope.list[index].choice=false;

				//循环遍历集合中的数据
				angular.forEach($scope.loanred,function(data,index,array){
					if(data.id==loanRecordId){
						//更新实际支付金额
						$scope.loanRedAmt=$scope.loanRedAmt-($scope.loanred[index].money);
						//删除集合对象中的投资券
						$scope.loanred.splice(index, 1);
					}
				});
				
			}else{
				//投资券使用数量控制
				if($scope.loanred.length>=2){
					var popup2 = $ionicPopup.alert({
		       			template: '最多使用2张投资券',
		       			title: '系统提示'
		     		});
					return;
				}
				//将状态更新为选中
				$scope.list[index].choice=true;
				
				//建立投资券对象放入集合
				var object = new Object();
				object.money = $scope.list[index].amount;
				object.id = $scope.list[index].id;
				$scope.loanred.push(object);
				//更新实际支付金额
				$scope.loanRedAmt+=$scope.list[index].amount;
			}
		}
		
	}//打开投资券功能结束


  //借给TA
	$scope.borrow=function(produceId,loanMoney,borrowMoney){
		var loanMoney = parseInt(loanMoney);
		//投资券验证
		if($scope.loanred.length>2){
			$ionicPopup.alert({title:'系统提示',template:'最多使用2张投资券...'});
			return ;
		}
		
		if(loanMoney==null||loanMoney==''){
			$ionicPopup.alert({title:'系统提示',template:'金额不能为空'});
			return ;
		}
		
		//验证投资金额 
		var r = /^\+?[1-9][0-9]*$/;
		if(!r.test(loanMoney)){
			$ionicPopup.alert({title:'系统提示',template:'金额输入错误'});
			return ;
		}
/*		if(loanRedAmt%50!=0){
			$ionicPopup.alert({title:'系统提示',template:'借出金额+投资卷金额之和只能为50的倍数'});
			return ;
		}*/
		if(loanMoney%50!=0){
				$ionicPopup.alert({title:'系统提示',template:'借出金额只能为50的倍数'});
				return ;
			}	

		
		//借出金额控制（不能大于尚需要借款金额）
		if(loanMoney>borrowMoney){
			$ionicPopup.alert({title:'系统提示',template:'借出金额必须小于用户借款金额'});
			return ;
		}
		
		//投资券id
		var reds = new Array();
		angular.forEach($scope.loanred,function(data,index,array){
			reds.push(data.id);
		})

/*	   if(reds.length==0){
		 	num=0;
		 }
		 if(reds.length==1){
		 	num=5;
		 loanMoney=parseInt(loanMoney)-5;
		 }
		 if(reds.length==2){
		 	num=10;
		 	loanMoney=parseInt(loanMoney)-10;
		 }*/
/*		console.log(loanMoney);*/
		//弹出确认对话款
	    var confirmPopup = $ionicPopup.confirm({
	       title: '用户确认',
	       cancelText: '取消',
	       okText: '确定',
	       template: '你确定借出该金额吗?'
	    });
	    confirmPopup.then(function(res) {
	       if(res) {
	       		//等待
	       		var loading =  $ionicLoading.show({
		      		template: '投资处理中,请您耐心等候...'
		    	});
				
				//保存投资
	       		LoanService.saveLoan(produceId,loanMoney,reds).then(function(response) {
					if(response.success=="success"){
						$ionicLoading.hide();
						//弹出提示并进行页面跳转到首页
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							$state.go("tab.zjr");
						});
				
					}else{
						$ionicLoading.hide();
						//只弹出页面提示
						$ionicPopup.alert({title:'系统提示',template:response.message});
						//清空投资券数据
						$scope.loanred = [];
						$scope.loanRedAmt = 0;
					}
				},function(e){
					$ionicLoading.hide();
					$ionicPopup.alert({title:'系统提示',template:'系统好像出了点故障，请稍后再试'});
				});
	       }
	    });

	}
	
})

//产品明细
.controller('ProduceDetailChangController', function($rootScope,$ionicPopup,$ionicModal,$ionicHistory,$ionicLoading,$scope,$stateParams,UserService,$window,$state,ZjrProduceService,LoanService,MyService,InvestmentService) {
	var produceId=$stateParams.produceId;
	
	//投资券获取方式
	$scope.showRule = function(){
		var alertPopup = $ionicPopup.alert({
       		template: '获取方式<br>'+
       		'1.新用户注册成功后,可获得5元投资券.<br>'+
       		'2.成功绑定自金融邀请码，邀请人可获得5元投资券，被邀请人获得5元投资券.<br>'+
       		'3.借款人粉丝数首次达到10的倍数时可获得10元投资券.<br>'+
       		'使用方式<br>'+
       		'1.单笔投资中，最多使用2张投资券<br>'+
       		'2.对同一借款人，每日只能一笔投资中使用投资券<br>'+
       		'平台将根据不同情况定期调整使用规则，敬请留意！',
	       	title: '投资券使用规则',
	       	cssClass:'my-custom-popup'
	    });
	}
	
	//查询用户信息,姓名，头像，有无逾期
	ZjrProduceService.getUserDetailByProduceId(produceId,1).then(function(response) {
		if(response.success=="success"){
			$scope.user = response.data;
		}
	});

	//查询借给他的信息
	LoanService.longLoanDetailList(produceId,0).then(function(response) {
		if(response.success=="success"){
			$scope.details = response.data;
		}
		if(response.data==null||response.data.length<=0){
			$scope.detailsShow=false;
		}else{
			$scope.detailsShow=true;
		}
	});

	//查询产品信息
	ZjrProduceService.getProduceDetailById(produceId).then(function(response) {
		if(response.success=="success"){
			$scope.produce = response.data;
		}
	});
	$scope.clistsize=[];
   $scope.crecharge=false;
	var balance=0;
	//查询帐户余额
	MyService.getAccountByUserId().then(function(response) {
		if(response.success=="success"){
			balance=response.data;
			//查询投资券有效金额
	     InvestmentService.getLoanRedList(0).then(function(response){
				if(response.data!=null){
					for(var i=0;i<response.data.length;i++){
						if(response.data[i].status==0){
						$scope.clistsize.push(response.data[i]);	
						}													
					}
					$scope.cinviteSize=$scope.clistsize.length;
	                if($scope.cinviteSize!=2&&balance<=40){
	                	//按钮变成去充值
	                	$scope.crecharge=true;
	                }
				}
			});
		}
		
	});
	//去充值
	$scope.goCrecharge=function(){	
			$rootScope.pay=1;
	       	$state.go('tab.my');
	}
	
	//验证是否可以借给他
	
	
	//计算到期后收益,并验证金额是否充足，合法。
	$scope.isOk=false;
	$scope.appointment=0;
	var confirmPopup;
	$scope.brorrowChange=function(principal,produce){
/*		 var b1 =  parseInt(balance)+"";
	      var b2  = parseInt(principal)+"";
		if(balance<50){
		//弹出提示信息
		if(principal.length==1){
			try{
	 	 confirmPopup.close();
	 	}catch(error){
	 		
	 	}	
	     confirmPopup = $ionicPopup.confirm({
	       title: '系统提示',
	       cancelText: '取消',
	       okText: '去充值',
	       template: '余额只有'+balance+'了！<br />'
	    });	
	    confirmPopup.then(function(res) {
	       if(res) {
	       	$state.go('tab.my');
	       	$rootScope.pay=1;
	      }
	     });
	  }  
    }else if(balance<principal && b1.length==b2.length){
    	try{
	 	 confirmPopup.close();
	 	}catch(error){
	 		
	 	}
    	  confirmPopup = $ionicPopup.confirm({
	       title: '系统提示',
	       cancelText: '取消',
	       okText: '去充值',
	       template: '余额只有'+balance+'了！<br />'
	    });	
	    confirmPopup.then(function(res) {
	       if(res) {
	       	$state.go('tab.my');
	       	$rootScope.pay=1;
	      }
	    }); 	
    }*/
		var days = new Date(produce.deadTime).getTime()-new Date().getTime();
		var deadDays=parseInt(days/(1000 * 60 * 60 * 24))+1;
		$scope.appointment=principal*((produce.interestRates/360)*deadDays);
		
		//验证帐户余额是否充足
		if(principal!=''&&principal>=principal&&balance>=50){
			if(principal>0&&principal%50==0){
				$scope.isOk=true;
			}else{
				$scope.isOk=false;
			}
		}else{
			$scope.isOk=false;
		}

	}
	
	//定义选择的投资卷,默认为集合对象
	var loanred=new Array();
	$scope.loanred=loanred;
	
	//初始化投资券分页信息
	var page=0;
	$scope.noMore=true;
	$scope.list=[];
	
	//使用投资券金额
	$scope.loanRedAmt = 0;
	//应扣金额
	$scope.realCost = 0;
	
	//打开投资券页面
	$scope.getLoanRedList=function(){
		
		//加载投资券数据
		$scope.loadList=function(){
			//查询投资券数据
			InvestmentService.getLoanRedList(page).then(function(response){
				$scope.$broadcast('scroll.infiniteScrollComplete');
				$scope.countData = response.countData;
				if(response.data!=null){
					if(response.data.length<=0){
						$scope.noMore=false;
						if(page==0){
							$scope.noData=true;
						}
					}else{
						for(var i=0;i<response.data.length;i++){
							$scope.list.push(response.data[i]);
						}
						page=page+1;
					}
				}
			});
		}
		
		//初始化投资券页面
		$ionicModal.fromTemplateUrl('templates/zjr/tzq.html', {
		    scope: $scope
		}).then(function(modal) {
		    $scope.modal = modal;
		    $scope.modal.show();
		});
	  	//关闭投资券方法
		$scope.closeModal = function() {
		    $scope.modal.hide();
		};
		
		//选中投资券
		$scope.changeChoice=function(index,loanRecordId){
			//如果当前状态为选中状态
			if($scope.list[index].choice){
				//更改为未选中状态
				$scope.list[index].choice=false;

				//循环遍历集合中的数据
				angular.forEach($scope.loanred,function(data,index,array){
					if(data.id==loanRecordId){
						//更新实际支付金额
						$scope.loanRedAmt=$scope.loanRedAmt-($scope.loanred[index].money);
						//删除集合对象中的投资券
						$scope.loanred.splice(index, 1);
					}
				});
				
			}else{
				//投资券使用数量控制
				if($scope.loanred.length>=2){
					var popup2 = $ionicPopup.alert({
		       			template: '最多使用2张投资券',
		       			title: '系统提示'
		     		});
					return;
				}
				//将状态更新为选中
				$scope.list[index].choice=true;
				
				//建立投资券对象放入集合
				var object = new Object();
				object.money = $scope.list[index].amount;
				object.id = $scope.list[index].id;
				$scope.loanred.push(object);
				//更新实际支付金额
				$scope.loanRedAmt+=$scope.list[index].amount;
			}
		}
		
	}//打开投资券功能结束

	//借给TA
	$scope.borrow=function(produceId,principal,borrowMoney){
		//投资券验证
		if($scope.loanred.length>2){
			$ionicPopup.alert({title:'系统提示',template:'最多使用2张投资券...'});
			return ;
		}
		
		if(principal==null||principal==''){
			$ionicPopup.alert({title:'系统提示',template:'金额不能为空'});
			return ;
		}
		
		//验证投资金额 
		var r = /^\+?[1-9][0-9]*$/;
		if(!r.test(principal)){
			$ionicPopup.alert({title:'系统提示',template:'金额输入错误'});
			return ;
		}
		
		if(principal%50!=0){
			$ionicPopup.alert({title:'系统提示',template:'借出金额只能为50的倍数'});
			return ;
		}
		
		//借出金额控制
		if(principal>borrowMoney){
			$ionicPopup.alert({title:'系统提示',template:'借出金额必须小于用户借款金额'});
			return ;
		}
		
		//投资券id
		var reds = new Array();
		angular.forEach($scope.loanred,function(data,index,array){
			reds.push(data.id);
		})

		//弹出确认对话款
	    var confirmPopup = $ionicPopup.confirm({
	       title: '用户确认',
	       cancelText: '取消',
	       okText: '确定',
	       template: '你确定借出该金额吗?'
	    });
	    confirmPopup.then(function(res) {
	       if(res) {
	       		//等待
	       		var loading =  $ionicLoading.show({
		      		template: '投资处理中,请您耐心等候...'
		    	});
				
				//保存投资
	       		LoanService.addLongLoan(produceId,principal,reds).then(function(response) {
					if(response.success=="success"){
						$ionicLoading.hide();
						//弹出提示并进行页面跳转到首页
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							$state.go("tab.zjr");
						});
				
					}else{
						$ionicLoading.hide();
						//只弹出页面提示
						$ionicPopup.alert({title:'系统提示',template:response.message});
						//清空投资券数据
						$scope.loanred = [];
						$scope.loanRedAmt = 0;
					}
				},function(e){
					$ionicLoading.hide();
					$ionicPopup.alert({title:'系统提示',template:'系统好像出了点故障，请稍后再试'});
				});
	       }
	    });

	}
	
	//到期收益列表
	$scope.getLoanPayBackPlan=function(principal,longProduceId){
		if(principal==null||principal==''){
			$ionicPopup.alert({title:'系统提示',template:'金额不能为空'});
			return ;
		}
		
		//验证投资金额 
		var r = /^\+?[1-9][0-9]*$/;
		if(!r.test(principal)){
			$ionicPopup.alert({title:'系统提示',template:'金额输入错误'});
			return ;
		}
		
		if(principal%50!=0){
			$ionicPopup.alert({title:'系统提示',template:'借出金额只能为50的倍数'});
			return ;
		}
		
		//还款计划查询
	 	ZjrProduceService.getLoanPayBackPlan(principal,longProduceId).then(function(response) {
			if(response.success=='success'){
				$scope.payBackPlans=response.data;
			}
			
		});
		
		//打开还款计划
		$ionicModal.fromTemplateUrl('templates/zjr/addPayBackPlans.html', {
		    scope: $scope,
		    animation: 'slide-in-up'
		}).then(function(modal) {
		    $scope.modal = modal;
		    $scope.modal.show();
		});
		
		//关闭还款计划方法
		$scope.closeModal = function() {
		    $scope.modal.hide();
		};
	}
	
})

//投借学院列表
.controller('ArticleController', function($ionicPopover,$timeout,$ionicPopup,$scope,$stateParams,$window,$state,ArticleService) {

	//初始化当前数据
	$scope.articles=[];//数据初始化
	var page=0;//初始化page为0
	$scope.noMore=true;//加载更多
	$scope.articleList = function(){
		 ArticleService.articleList(page).then(function(response){
        console.log(response);
		 	for(var i=0;i<response.data.length;i++){
		 		response.data[i].titleImg=response.data[i].titleImg.replace('zjr.','txwl.');
		 		response.data[i].titleImg=response.data[i].titleImg.replace('80','8066');
		 		response.data[i].titleImg=response.data[i].titleImg.replace('806666','8066');
		 	}
		 	$scope.$broadcast('scroll.infiniteScrollComplete');
		 	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.noMore=false;
					if(page==0){
						$scope.noData=true;
					}
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.articles.push(response.data[i]);
					}
					page=page+1;
				}
			}
		})
	}
	
	//正文
	$scope.toArticleDetail = function(id,title,time){
		$state.go('tab.article',{"articleId":id,"title":title,"time":time});
	}
})

//投借学院正文
.controller('ArticleDetailController', function($sce,$ionicLoading,$ionicPopover,$timeout,$ionicPopup,$scope,$stateParams,$window,$state,ArticleService) {
	$scope.html = "";
	var articleId = $stateParams.articleId;
	var title = $stateParams.title;
	var time = $stateParams.time;
	$scope.title = title;
	$scope.time = time;
	
	ArticleService.articleDetail(articleId).then(function(response){
			var loading = $ionicLoading.show({
      			template: '请稍候',
    		})
			 if(response.success=='success'){
			 	 $scope.html =  $sce.trustAsHtml(response.data);
			 	 $ionicLoading.hide();
			 }else{
			 	 $ionicLoading.hide();
			 }
	});
})

//帮助正文控制器
.controller('HelpDetailController', function($scope,$stateParams,$state) {
	var state = $stateParams.state;
	$scope.title = "hide";
	if(state==1){
		$scope.name = "天下无赖平台介绍";
		$scope.content = "“天下无赖”是中国诚信联盟旗下，集“借款”、“投资”、“信用黑名单”、“民间征信”于一体的，金融一站式服务平台<br>"+
"特色一：额度你掌控<br>"+

"平台首创“额度养成模式”借款人通过日常的“借/还”款等操作逐步提升自身额度，培养良好的“借/还”款习惯<br>"+

"特色二：借款“利息、时长、金额”随心意<br>"+

"借款人可根据自己的实际用款情况，订制自己的借款“利息、时长、金额”。最短借款时长1天，利息低至日率0.4%<br>"+

"特色三：粉丝助力满标快<br>"+

"平台首创“粉丝机制”借款人通过良好还款表现，吸引投资人“关注”。同时增加自己的“粉丝”数，“粉丝”越多满标越快<br>"+

"特色四：“躺赚”终身制<br>"+

"邀请好友使用“天下无赖”并绑定自己的邀请码，被邀请人只要在平台产生“交易”，你都将获得相应的“邀请奖励”奖励终身领取！<br>"+

"特色五：多维度认证，风控看得见<br>"+

"平台通过黑名单系统以及前置审核机制，最大限度筛选借款用户，同时提供多达15项以上的权威认证以及多项用户数据，供投资人参考。风控看得见，投资更明白！<br>"+

"特色六：投资灵活，收益全网最强<br>"+

"投资100最高日赚3元，标期灵活，最短1天返本付息。即投即起息，资金不站岗<br>"+

"结语<br>"+
"人生之路，或许坎坷或许跌宕起伏！幸福或许短暂，困难还要面对！但无论怎样信用都将伴随每一个人的成长，幸福时它默默守护这你，困难时它将是你最有力的支柱！信用并不是几页资料几个数字，它是人与人之间最宝贵的财富！也是你最值得珍视的财富！<br>"+
"记住！信用，才是您最宝贵的财富！		";

	}
	if(state==2){
		$scope.name = "借、投相关说明";
		$scope.content = "投资<br>"+
"1.平台大数据筛查，最大限度排除黑名单用户和当前逾期用户<br>"+
"2.即投即生息，利息从投资成功开始计算<br>"+
"3.出借前可以查看借款人的资料提交情况、历史借款记录和相关信用信息，有效判断借款人风险情况<br>"+

"借款<br>"+
"1.即借即用款，比如借款人借款500元，已获取出借金额有300元，借款人可以随时提现已获金额。<br>"+
"2.量体裁衣，在自己的可承受范围内灵活定制自己的借款需求<br>"+
"3.借款人出现逾期，信用身价以借款金额的5%进行每天扣除（扣除下限为500，不足500不扣减），请借款人珍爱身价，远离逾期<br>"+
"4.借款人每获得一个粉丝，信用身价+10；每失去一个粉丝，信用身价-10<br>"+
"5.借款人当前借款没有结清不能进行借款 <br>"+
"6.天下无赖长贷功能，LV2等级以上才开放<br>"+

"违约信息公示<br>"+
"1.出借款项违约超过3天，借款人个人信息进入信用黑名单向网络公示，并会快速被各大搜索引擎收录<br>"+
"2.逾期第5天起，开始向用户通话联系人批量发送逾期入黑“专属”链接页面短信，（第五天3个，第六天6个...，依次递增）<br>"+

"违约催收<br>"+
"出借款项逾期10天后，平台人工介入免费催收，帮助出借人以年化36%收益向借款人进行欠款催讨。<br>"
	}
	if(state==3){
		$scope.name="5 平台服务费";
		$scope.content = "1.向“借款人”收取平台服务费，计算如下：<br>"+
       " 平台服务费=借款金额 x 比例<br>"+
       " 基础比例为3%,每升一个等级，降0.25%<br>"+
"2.向“出借人”收取平台服务费，收益到账才收取，不足0.1元，按0.1元收取，计算如下：<br>"+
   " 平台服务费=出借收益 x 10%";
	}
	if(state==4){
		$scope.name="如何关注借款人";
		$scope.content = "关注步骤如下:<br>"+
"1.点击“我的”进入“我的”界面<br>"+
"2.在“我的”界面点击“总借出”，进入“借出”界面<br>"+
"3.在“借出”界面，点击“已收回”，进入“已收回”界面，就可以关注TA";
	}
	if(state==5){
		$scope.name="放款小技巧";
		$scope.content = "1.参考借款人基本资料认证。<br>"+
		"2.参考借款人历史贷款记录。<br>"+
		"3.根据自己的风险承受能力及喜好，分散并小额出借。<br>"+
		"4.出借的时长以及利息的选择，请合理搭配。<br>"+
		"5.重视平台建议的审查维度(高级认证)。<br>"+
		"6.重视借款人的负债率。<br>"+
		"7.尽量出借给已关注的诚信借款人。";
	}
	if(state==6){
		$scope.name="借款小技巧";
		$scope.content ="1.尽量多地参与平台各类信用认证，提高信用身价。<br>"+
		"2.作为新用户，设置较低的单笔借款金额，以加速借款成功。<br>"+
		"3.尽量在承受范围内设置短期、高利率借款。<br>"+
		"4.保持良好还款记录,粉丝量多,能够提高借款成功率。<br>"+
		"5.良好的还款记录达到一定的笔数后，可适当提高借款金额,降低借款利率。<br>"+
		"6.升级Lv2后可向机构借款，享受低利率，高额度，秒放款的借款服务。<br>"+
		"7.级别越高，借款金额越高，利率越低，用款成本大幅降低。";
	}
	if(state==7){
		$scope.name="充值、提现、还款注意";
		$scope.content = "1.	充值注意<br>"+
"1)	平台目前支持“支付宝”“银行卡”充值<br>"+
"2)	首次充值请在“充值页面”仔细查看相关教程，若“充值”遇到问题请添加“天下无赖诚信联盟”微信公众号联系我们<br>"+

"2.提现注意<br>"+
"提现到账时间一般为：9:00-21:00,若“提现”遇到问题，请添加“天下无赖诚信联盟”微信公众号联系我们<br>"+

"3.还款注意<br>"+
"1)	所有的还款，都需要在天下无赖APP中完成，切莫给Ta人转账，防止个人资金受损。<br>"+
"2)	还款提醒：出借款项到期前3天至逾期10天内，平台自动向借款人发送催收短信、彩信和语音进行还款提醒<br>"+
"<p class='myRed'>3)	长贷—提前还款：<br>"+
"&nbsp;&nbsp;&nbsp;1.借款30天后才可以使用提前还款功能<br>"+
" &nbsp;&nbsp;&nbsp;2.提前还是指一次还清所有未还借款<br>"+
"4)	长贷—分期还款：需要到达分期月时间才能进行还款</p>";
	}
	if(state==9){
		/*$scope.name="邀请功能介绍";
		$scope.content = "邀请人可以从被邀请人处获取收益，具体如下：<br>"+
"当用户绑定邀请人的“邀请码”后，无论“借款”或者“投资”，邀请人都可获得收益，收益计算：<br>"+
"1.可获被邀请人每笔“投资”金额的千分之五（收益长期有效）<br>"+
"2.可获被邀请人每笔“借款”利息的百分之五（收益长期有效）<br>"+

"成功邀请好友绑定“邀请码”，被邀请人信用身价+50；邀请人信用身价+25（上限250）<br>"+
"操作步骤：<br>"+
"1.点击“我的”进入我的页面<br>"+
"2.在“我的”页面点击“邀请码”<br>"+
"3.进入“邀请码”页面，复制邀请码，将邀请码发送给好友";*/
	$scope.name="邀请赚钱机制介绍";
	$scope.content = "成功邀请好友，邀请人和被邀请人均可获取收益，具体如下：<br>"+
"一、天下无赖注册用户可生成邀请码，通过邀请码可邀请好友注册天下无赖，获得长期收益；<br>"+
"二、当B客户绑定A客户的“邀请码”后，无论B客户“借款”或者“投资”，A客户都可以获得收益，收益计算：<br>"+
"1.A客户可获B客户每笔“投资”金额的千分之五（收益长期有效）<br>"+
"2.A客户可获B客户每笔“借款”利息的百分之五（收益长期有效）<br>"+
"三、当B客户成功邀请C客户绑定“邀请码”后，无论C客户“借款”或者“投资”，A客户仍然可以获得收益，收益计算：<br>"+
"1.A客户可获C客户每笔“投资”金额的千分之三（收益长期有效）<br>"+
"2.A客户可获C客户每笔“借款”利息的百分之三（收益长期有效）<br>"+
"四、绑定邀请码，被邀请人完成实名认证后，邀请人可获得5元投资卷<br>"+
"操作步骤：<br>"+
"1.	点击“我的”进入我的页面<br>"+
"2.	在“我的”页面点击“邀请码”<br>"+
"3.	进入“邀请码”页面，复制邀请码，将邀请码发送给好友;"
	}
	if(state==10){
		$scope.name = "天下无赖借款额度";
		$scope.content = "1.LV1等级用户，在天下无赖中借款额度为3000<br>"+
		"2.LV2等级用户，在天下无赖中借款额度为6000<br>"+
		"3.LV3等级用户，在天下无赖中借款额度为10000<br>"+
		"4.LV4等级用户，在天下无赖中借款额度为20000<br>"+
		"5.LV5等级用户，在天下无赖中借款额度为40000<br>"+
		"6.其它等级敬请期待！";
	}
})

;